package com.sh.common.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class FileUtil {

    public static final String ALGORITHM_SHA256 = "SHA-256";

    public static final String ALGORITHM_MD5 = "MD5";

    public static String generateFileOssKey(String filename) {
        return "studio/file/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "/" + filename;
    }

    public static String generateOperatorFileOssKey(String operatorName, String filename) {
        return "studio/operator/" + operatorName + "/" + filename;
    }

    public static String generateAlgoSchemaOssKey(Long algoId) {
        return "studio/algo/" + algoId + "/data.json";
    }

    public static String calFileFingerPrint(InputStream in, String algorithm) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            DigestInputStream digestInputStream = new DigestInputStream(in, digest);
            byte[] buffer = new byte[8192];
            while (digestInputStream.read(buffer) != -1) {
                digest.update(buffer);
            }
            byte[] bytes = digest.digest();
            return bytesToHex(bytes);
        } catch (Exception e) {
            log.error("文件指纹生成失败", e);
            return null;
        }
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

}
